<template>
    <div>
         <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
         <!-- 卡片列表 -->
         <el-card>
             <el-alert
                title="添加商品信息"
                type="info" show-icon center :closable="false">
            </el-alert>
            <!-- 步骤条 -->
            <el-steps :active="activeIndex-0" finish-status="success" align-center>
              <el-step title="基本信息"></el-step>
              <el-step title="商品参数"></el-step>
              <el-step title="商品属性"></el-step>
              <el-step title="商品图片"></el-step>
              <el-step title="商品内容"></el-step>
              <el-step title="完成"></el-step>
            </el-steps>
          
            <!-- tab页签 -->
            <el-form label-position="top" label-width="80px" :model="addGoodsForm" :rules="addGoodsRule" ref="addGoodsRef">
              <el-tabs tab-position="left" v-model="activeIndex" :before-leave="beforeTabLeave" @tab-click="tabClick">
                <el-tab-pane label="基本信息" name="0">
                  <el-form-item label="商品名称" prop="goods_name">
                    <el-input v-model="addGoodsForm.goods_name"></el-input>
                  </el-form-item>
                  <el-form-item label="商品价格" prop="goods_price">
                    <el-input type="number"
                    v-model="addGoodsForm.goods_price"></el-input>
                  </el-form-item>
                  <el-form-item label="商品重量" prop="goods_weight">
                    <el-input type="number" v-model="addGoodsForm.goods_weight"></el-input>
                  </el-form-item>
                  <el-form-item label="商品数量" prop="goods_number">
                    <el-input type="number" v-model="addGoodsForm.goods_number"></el-input>
                  </el-form-item>
                  <el-form-item label="商品分类" prop="goods_number">
                    <el-cascader
    v-model="addGoodsForm.goods_cat"
    :options="cateList" :props="cateProp"
    @change="handleChange"></el-cascader>
                  </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品参数" name="1">
                  <el-form-item :label="item.attr_name" v-for="item in manyData" :key="item.attr_id">
                     <el-checkbox-group v-model="item.attr_vals">
                    <el-checkbox v-for="(param,i) in item.attr_vals" :key="i" :label="param" border></el-checkbox>
                  </el-checkbox-group>
                    
                  </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品属性" name="2">
                  <el-form-item v-for="item in onlyData" :key="item.attr_id" :label="item.attr_name">
                    <el-input v-model="item.attr_vals"></el-input>
                  </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品图片" name="3">
                  <el-upload
                  class="upload-demo"
                  action="http://127.0.0.1:8888/api/private/v1/upload"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  list-type="picture" :headers="headerObj" :on-success="handleSuccess">
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
                <el-dialog title="图片预览"
                  :visible.sync="previewVisible"
                  width="50%">
                  <img style="width:100%" :src="previewPath" />
                 </el-dialog>
                </el-tab-pane>
                                
                <el-tab-pane label="商品内容" name="4">
                  <!-- 富文本编辑器组件 -->
                  <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
                  <!-- 添加商品按钮 -->
                  <!-- 添加商品按钮 -->
                  <el-button type="primary" class="btnAdd" @click="submitAddGoods">添加商品</el-button>
                </el-tab-pane>
              </el-tabs>
            </el-form>
         </el-card>
    </div>
</template>

<script>
export default {
  data() {
    return {
      activeIndex:0,
      // 添加商品表单
      addGoodsForm:{
        goods_name:'',
        goods_price:0,
        goods_weight:0,
        goods_number:0,
        // 级联选择器选中值
        goods_cat:[],
        // 上传图片列表
        pics:[],
        // 商品详情描述
        goods_introduce:"",
        attrs:[]
      },
      // 商品参数规则
      addGoodsRule:{
        goods_name:[
           { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price:[
           { required: true, message: '价格不能为空'},
         
        ],
        goods_weight:[
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number:[
          { required: true, message: '必填项', trigger: 'blur' }
        ]
      },
      cateList:[],
      // 级联选择器设置
      cateProp:{
        expandTrigger:'hover',
        label:'cat_name',
        value:'cat_id'
      },
      // 动态参数列表
      manyData:[],
      //静态属性列表
      onlyData:[],
      // 上传图片配置请求头
      headerObj:{
        Authorization:sessionStorage.getItem('token')
      },
      // 图片预览路径
      previewPath:"",
      previewVisible:false

    }
  },

  created() {
    this.getCateList();
  },

  methods: {
    //   获取商品分类数据
    async getCateList(){
        const {data:res}=await this.$axios.get('categories')
        if(res.meta.status!=200) return this.$message.error('获取失败')
        this.cateList=res.data
    },
    handleChange(){
      if(this.addGoodsForm.goods_cat.length!=3)
      {
       return this.addGoodsForm.goods_cat=[]
      }
   
    },
    // tab标签离开前一个标签的切换事件
    beforeTabLeave(newActive,oldActive){
      if(oldActive==0&&this.addGoodsForm.goods_cat.length!=3){
        this.$message.error('请选择三级商品分类')
        return false;
      }
      
    },
    // tab标签点击事件 day07完成
    async tabClick(){
     
      if(this.activeIndex==1){
        // 进入动态参数页面
        const {data:res}=await this.$axios.get(`categories/${this.addGoodsForm.goods_cat[2]}/attributes`,{params:{sel:'many'}})
        if(res.meta.status!=200) return this.$message.error('获取失败')
        res.data.forEach(item => {
          item.attr_vals=item.attr_vals==""?[]:item.attr_vals.split(' ')
        });
        this.manyData=res.data
      
      }else if(this.activeIndex==2)
      { //进入静态属性页面
        const {data:res}=await this.$axios.get(`categories/${this.addGoodsForm.goods_cat[2]}/attributes`,{params:{sel:'only'}})
        if(res.meta.status!=200) return this.$message.error('获取失败')
        this.onlyData=res.data
      }
    },
    // 点击预览图片事件
    handlePreview(files){
    this.previewPath=files.response.data.url
    this.previewVisible=true;
    },
    //点击图片删除事件
    handleRemove(files){
      const tmp_path=files.response.data.tmp_path;
      const i=this.addGoodsForm.pics.findIndex(x=>{
      x.pic==tmp_path
      })
      this.addGoodsForm.pics.splice(i,1)
    },
    //上传图片成功时触发
    handleSuccess(res){
     
      if(res.meta.status!=200)return this.$message.error('上传失败');
      this.addGoodsForm.pics.push({pic:res.data.tmp_path})
    },
    submitAddGoods(){
      this.$refs.addGoodsRef.validate(async (flag,col)=>{
        if(!flag) return this.$message.error('请填写必填项')
        this.manyData.forEach(item=>{
          this.addGoodsForm.attrs.push({
            "attr_id":item.attr_id,
            "attr_value":item.attr_vals.join(' ')
          })
        })
        this.onlyData.forEach(item=>{
          this.addGoodsForm.attrs.push({
            "attr_id":item.attr_id,
            "attr_value":item.attr_vals
          })
        })
        const form=JSON.parse(JSON.stringify(this.addGoodsForm))
        form.goods_cat=form.goods_cat.join(',')
        const {data:res}=await this.$axios.post('goods',form)
         if(res.meta.status!=201) return this.$message.error(res.meta.msg)
         this.$message.success('添加成功')
         this.$router.push('/goods')
      })
      
      
    }
  }
};
</script>

<style scoped lang='less'>
.el-checkbox{
  margin-right: 0px;
}
.btnAdd{
  margin-top: 10px;
}
</style>
